package com.example.teemor.es_demo.controller;

import com.example.teemor.es_demo.entity.ProductMySQL;
import com.example.teemor.es_demo.entity.ProductES;
import com.example.teemor.es_demo.service.ProductService;
import com.example.teemor.es_demo.service.UserBehaviorService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

import com.example.teemor.es_demo.controller.UserController.ApiResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

 
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/client/products")
@RequiredArgsConstructor
public class ProductController {
    
    private final ProductService productService;
    private final UserBehaviorService userBehaviorService;



    /**
     * 获取所有商品（分页，从ES）
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<ProductES>>> getAllProducts(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Pageable pageable = PageRequest.of(page, size);
            Page<ProductES> products = productService.findAllES(pageable);
            return ResponseEntity.ok(ApiResponse.success(products, "获取商品列表成功"));
        } catch (Exception e) {
            log.error("Failed to get all products", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 根据ID获取商品
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<ProductMySQL>> getProductById(
            @PathVariable Long id,
            @RequestParam(required = false) Long userId,
            HttpServletRequest request) {
        try {
            ProductMySQL product = productService.findByIdMySQL(id)
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            
            // 记录商品浏览行为
            if (userId != null) {
                userBehaviorService.recordProductView(userId, request.getSession().getId(), 
                        id, product.getCategory(), request);
            }
            
            return ResponseEntity.ok(ApiResponse.success(product, "获取商品成功"));
        } catch (Exception e) {
            log.error("Failed to get product by id: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }





    /**
     * 搜索商品（Elasticsearch）
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<Iterable<ProductES>>> searchProducts(
            @RequestParam String keyword,
            @RequestParam(required = false) Long userId,
            HttpServletRequest request) {
        try {
            Iterable<ProductES> products = productService.searchES(keyword);
            
            // 记录搜索行为
            if (userId != null) {
                userBehaviorService.recordSearch(userId, request.getSession().getId(), 
                        keyword, "product", request);
            }
            
            return ResponseEntity.ok(ApiResponse.success(products, "搜索商品成功"));
        } catch (Exception e) {
            log.error("Failed to search products with keyword: {}", keyword, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 根据分类获取商品（从ES）
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<ApiResponse<List<ProductES>>> getProductsByCategory(
            @PathVariable String category) {
        try {
            List<ProductES> products = productService.findByCategoryES(category);
            return ResponseEntity.ok(ApiResponse.success(products, "获取分类商品成功"));
        } catch (Exception e) {
            log.error("Failed to get products by category: {}", category, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 根据品牌获取商品（从ES）
     */
    @GetMapping("/brand/{brand}")
    public ResponseEntity<ApiResponse<List<ProductES>>> getProductsByBrand(
            @PathVariable String brand) {
        try {
            List<ProductES> products = productService.findByBrandES(brand);
            return ResponseEntity.ok(ApiResponse.success(products, "获取品牌商品成功"));
        } catch (Exception e) {
            log.error("Failed to get products by brand: {}", brand, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 获取商品统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getProductStats() {
        try {
            List<String> categories = productService.getAllCategories();
            List<String> brands = productService.getAllBrands();
            
            Map<String, Object> stats = Map.of(
                    "categories", categories,
                    "brands", brands,
                    "timestamp", System.currentTimeMillis()
            );
            
            return ResponseEntity.ok(ApiResponse.success(stats, "获取商品统计成功"));
        } catch (Exception e) {
            log.error("Failed to get product stats", e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 商品点击记录
     */
    @PostMapping("/{id}/click")
    public ResponseEntity<ApiResponse<Void>> recordProductClick(
            @PathVariable Long id,
            @RequestParam Long userId,
            HttpServletRequest request) {
        try {
            ProductMySQL product = productService.findByIdMySQL(id)
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            
            userBehaviorService.recordClick(userId, request.getSession().getId(), 
                    id, product.getCategory(), request);
            
            return ResponseEntity.ok(ApiResponse.success(null, "商品点击记录成功"));
        } catch (Exception e) {
            log.error("Failed to record product click: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }

    /**
     * 加入购物车记录
     */
    @PostMapping("/{id}/add-cart")
    public ResponseEntity<ApiResponse<Void>> recordAddToCart(
            @PathVariable Long id,
            @RequestParam Long userId,
            HttpServletRequest request) {
        try {
            ProductMySQL product = productService.findByIdMySQL(id)
                    .orElseThrow(() -> new RuntimeException("商品不存在"));
            
            userBehaviorService.recordAddToCart(userId, request.getSession().getId(), 
                    id, product.getCategory(), request);
            
            return ResponseEntity.ok(ApiResponse.success(null, "加购物车记录成功"));
        } catch (Exception e) {
            log.error("Failed to record add to cart: {}", id, e);
            return ResponseEntity.badRequest().body(ApiResponse.error(e.getMessage()));
        }
    }
}